import 'dart:io';

import '06-Class.dart';

void main() {
  const oneSecond = Duration(seconds: 1);

  Future<void> printWithDelay(String msg) async {
    await Future.delayed(oneSecond);
    print(msg);
  }

  //原始写法，回调地狱
  Future<void> printWithDelay2(String message) {
    return Future.delayed(oneSecond).then((_) {
      print(message);
    });
  }

  printWithDelay("1s msg.");

  Future<void> createDescriptions(Iterable<String> objects) async {
    for (final object in objects) {
      try {
        var file = File('$object.txt');
        if (await file.exists()) {
          var modified = await file.lastModified();
          print(
              'File for $object already exists. It was modified on $modified.');
          continue;
        }
        await file.create();
        await file.writeAsString('Start describing $object in this file.');
      } on IOException catch (e) {
        print('Cannot create description for $object: $e');
      }
    }
  }

  List<String> tmpFiles = [];
  for (int i = 0; i < 7; i++) {
    tmpFiles.add("temp-file-$i");
  }
  createDescriptions(tmpFiles);

  Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
    for (final object in objects) {
      await Future.delayed(oneSecond);
      yield '${craft.name} flies by $object';
    }
  }

  report(Spacecraft("name", DateTime.now()), ["a", "c"]);
}
